import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  TreeSelect,
  Row,
  Col,
  Space,
  Typography,
  Tag,
  InputNumber,
  Button,
} from 'antd';
import { ApartmentOutlined, UserOutlined } from '@ant-design/icons';
import { Department, DepartmentForm as DepartmentFormData } from '../../types/rbac';
import { departmentApi } from '../../services/cloud/api/departmentApi';

const { TextArea } = Input;
const { Option } = Select;
const { Text } = Typography;

interface DepartmentFormProps {
  visible: boolean;
  department?: Department;
  departmentTree?: Department[];
  treeLoading?: boolean;
  onSubmit: (values: DepartmentFormData) => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
}

const DepartmentForm: React.FC<DepartmentFormProps> = ({
  visible,
  department,
  departmentTree = [],
  treeLoading = false,
  onSubmit,
  onCancel,
  loading = false,
}) => {
  const [form] = Form.useForm();
  const [users, setUsers] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(false);

  // 加载用户数据
  useEffect(() => {
    if (visible) {
      loadUsers();
    }
  }, [visible]);

  const loadUsers = async () => {
    try {
      setLoadingData(true);
      const usersRes = await departmentApi.getDepartmentManagers().catch((err: any) => {
        console.warn('加载部门管理员数据失败:', err);
        return [];
      });
      console.log('部门管理员数据:', usersRes); // 添加调试日志
      console.log('数据类型:', typeof usersRes, Array.isArray(usersRes)); // 检查数据类型
      if (Array.isArray(usersRes) && usersRes.length > 0) {
        console.log('第一个用户数据:', usersRes[0]); // 查看第一个用户的数据结构
      }
      setUsers(Array.isArray(usersRes) ? usersRes : []);
    } catch (error) {
      console.error('加载数据失败:', error);
      setUsers([]);
    } finally {
      setLoadingData(false);
    }
  };

  useEffect(() => {
    if (visible) {
      if (department) {
        form.setFieldsValue({
          name: department.name,
          code: department.code,
          description: department.description,
          parentId: department.parentId,
          managerId: department.managerId || department.manager?.id,
          sort: department.sort,
          status: department.status,
          phone: department.phone,
          email: department.email,
        });
      } else {
        form.resetFields();
      }
    }
  }, [visible, department, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 数据预处理
      const submitData = {
        ...values,
        // 确保数值类型正确
        sort: Number(values.sort) || 1,
        status: Number(values.status),
        // 处理可选字段
        parentId: values.parentId || null,
        managerId: values.managerId || null,
        phone: values.phone?.trim() || null,
        email: values.email?.trim() || null,
        description: values.description?.trim() || null,
      };
      
      await onSubmit(submitData);
      form.resetFields();
    } catch (error: any) {
      if (error?.errorFields) {
        console.error('表单验证失败:', error.errorFields);
        // 聚焦到第一个错误字段
        const firstErrorField = error.errorFields[0];
        if (firstErrorField?.name) {
          form.scrollToField(firstErrorField.name);
        }
      } else {
        console.error('提交失败:', error);
      }
    }
  };

  // 构建部门树选择数据
  const buildDepartmentTreeData = (departments: Department[], excludeId?: string): any[] => {
    console.log('构建部门树数据:', departments, '排除ID:', excludeId); // 添加调试日志
    return departments
      .filter(dept => dept.id !== excludeId) // 排除当前编辑的部门
      .map(dept => ({
        title: dept.name,
        value: dept.id,
        children: dept.children ? buildDepartmentTreeData(dept.children, excludeId) : [],
      }));
  };

  const treeData = buildDepartmentTreeData(departmentTree, department?.id);
  console.log('最终树数据:', treeData); // 添加调试日志

  return (
    <Modal
      title={
        <Space>
          <ApartmentOutlined />
          <span>{department ? '编辑部门' : '新建部门'}</span>
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={900}
      style={{ top: 20 }}
      destroyOnClose
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFinish={handleSubmit}
        initialValues={{
          status: 1,
          sort: 1,
          roles: [],
        }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="部门名称"
              name="name"
              rules={[
                { required: true, message: '请输入部门名称' },
                { min: 2, max: 50, message: '部门名称长度为2-50个字符' },
              ]}
            >
              <Input placeholder="请输入部门名称，如：技术部" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="部门代码"
              name="code"
              rules={[
                { required: true, message: '请输入部门代码' },
                { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '部门代码只能包含字母、数字、下划线，且不能以数字开头' },
                { min: 2, max: 30, message: '部门代码长度为2-30个字符' },
              ]}
            >
              <Input placeholder="请输入部门代码，如：tech_dept" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="上级部门"
              name="parentId"
            >
              <TreeSelect
                placeholder="请选择上级部门（可选）"
                allowClear
                treeData={treeData}
                loading={treeLoading}
                showSearch
                treeNodeFilterProp="title"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="部门负责人"
              name="managerId"
            >
              <Select placeholder="请选择部门负责人（可选）" allowClear showSearch loading={loadingData}>
                {users.map(user => (
                  <Option key={user.id} value={user.id}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
                      <UserOutlined style={{ color: '#1890ff', flexShrink: 0 }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ 
                          fontWeight: 500, 
                          color: '#262626', 
                          lineHeight: 1.4, 
                          marginBottom: 2,
                          fontSize: 14 
                        }}>
                          {user.realName || user.username || '未知用户'}
                        </div>
                        <div style={{ 
                          color: '#8c8c8c', 
                          fontSize: 12, 
                          lineHeight: 1.2,
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }}>
                          {user.email || '无邮箱'}
                        </div>
                      </div>
                    </div>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="联系电话"
              name="phone"
              rules={[
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
              ]}
            >
              <Input placeholder="请输入联系电话" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="邮箱地址"
              name="email"
              rules={[
                { type: 'email', message: '请输入正确的邮箱地址' },
              ]}
            >
              <Input placeholder="请输入邮箱地址" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="排序"
              name="sort"
              rules={[{ required: true, message: '请输入排序值' }]}
            >
              <InputNumber
                placeholder="请输入排序值"
                min={1}
                max={999}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="状态"
              name="status"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select placeholder="请选择状态">
                <Option value={1}>
                  <Space>
                    <Tag color="success">启用</Tag>
                    <span>正常使用</span>
                  </Space>
                </Option>
                <Option value={0}>
                  <Space>
                    <Tag color="default">禁用</Tag>
                    <span>暂停使用</span>
                  </Space>
                </Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row>
          <Col span={24}>
            <Form.Item
              label="部门描述"
              name="description"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
              rules={[
                { max: 200, message: '描述长度不能超过200个字符' },
              ]}
            >
              <TextArea
                placeholder="请输入部门描述，如：负责产品研发和技术支持"
                rows={3}
                showCount
                maxLength={200}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row>
          <Col span={24}>
            <Form.Item wrapperCol={{ offset: 3, span: 21 }}>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  {department ? '更新' : '创建'}
                </Button>
                <Button onClick={onCancel}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default DepartmentForm;